<?php

namespace App\Http\Models\Rotation;

use App\Common\Utils\Common;
use App\Http\Models\Rotation\Rotation;

class RotationService
{

    public function index($request) {
        $rotationDatas = Rotation::select()
                ->where('name', 'like', '%' . $request->name . '%')
                ->orderBy('created_at', 'desc')
                ->paginate(PAGES);
        foreach ($rotationDatas as $key => $val) {
            $rotationDatas[$key]->created_at = date("Y-m-d H:i:s", $val->created_at);
        }
        return $rotationDatas;
    }

    public function store($request) {
        $data = [
            'name' => $request->name,
            'sort' => $request->sort,
            'synopsis' => $request->synopsis??'',
            'status' => $request->status,
            'images' => $request->images,
            'created_at' => time()
        ];
        try {
            $res = Rotation::create($data);
            if ($res->id) {
                Common::success(INSERT_SUCCES);
                return $res;
            } else {
                Common::success(INSERT_ERROR);
            }
        } catch (Exception $ex) {
            Common::error(INSERT_ERROR);
        }
    }

    public function updateSave($request, $id) {
        $data = [
            'name' => $request->name,
            'sort' => $request->sort,
            'synopsis' => $request->synopsis??'',
            'status' => $request->status,
            'images' => $request->images,
            'created_at' => time()
        ];
        try {
            $res = Rotation::where('id', decryptUrl($id))->update($data);
            if ($res) {
                Common::success(UPDATE_SUCCES);
                return $res;
            } else {
                Common::error(UPDATE_ERROR);
            }
        } catch (Exception $ex) {
            Common::error(UPDATE_ERROR);
        }
    }

    public function show($id) {
        $userData = Rotation::where('id', decryptUrl($id))->first();
        $userData->tmpImages = $userData->images;
        //$userData->images = IMAGE_HOST_URL . $userData->images;
        return $userData;
    }

    public function remove($id) {
        return Rotation::where('id', decryptUrl($id))->delete();
    }

}
